-- Create a new dissector
MPLSCWFR = Proto ("mplscwfr", "MPLS with codeword with fr")

f_reserved = ProtoField.uint8 ("mplscwfr.reserved", "Reserved", base.HEX, nil, 0xF0)
f_flags = ProtoField.uint8 ("mplscwfr.flags", "Flags",  base.HEX, nil, 0x0F)
f_frag = ProtoField.uint8 ("mplscwfr.frag", "Fragment", base.HEX, nil, 0xC0)
f_len = ProtoField.uint8 ("mplscwfr.len", "Length", base.HEX, nil, 0x3F)
f_lenval = ProtoField.uint8 ("mplscwfr.lenval", "LengthVal", base.DEC, nil, 0x3F)
f_sequence_num = ProtoField.uint32 ("mplscwfr.sequence_num", "Sequence Number")

MPLSCWFR.fields = { f_reserved, f_flags, f_frag, f_len, f_lenval, f_sequence_num } 


-- The dissector function

function MPLSCWFR.dissector (buffer, pinfo, tree)

-- Fetch data from the packet
local codeword = buffer(0,4)
local codeword_val = codeword:uint()

local reserved = buffer(0,1):bitfield(0,4)
local flags = buffer(0,1):bitfield(4,4)
local frag = buffer(1,1):bitfield(0,2)
local len = buffer(1,1):bitfield(2,6)

local lenval = f_lenval.value
 
--local fr_len = len:uint()
local sequence_num = buffer(2,2):uint()

local subtree = tree:add (MPLSCWFR, buffer())
subtree:add (f_reserved, reserved)
subtree:add (f_flags, flags)
subtree:add (f_frag, frag)
subtree:add (f_len, len)
subtree:add (f_sequence_num, sequence_num)

local endbuf = buffer:len()

local next_tvb = 0

--if len ~= 0 and len >= endbuf then
--   print ("*** len="..len)
--   print ("*** endbuf="..endbuf)
--end

if len ~= nil and len > 0 and len < endbuf then
   next_tvb = buffer(4, len - 4):tvb()
else
   next_tvb = buffer(4):tvb()
end

next_dissector = Dissector.get ("pw_hdlc_nocw_fr")
next_dissector:call (next_tvb, pinfo, tree)

end

-- Register the dissector

mpls_table = DissectorTable.get ("mpls.label")
mpls_table:add (4294967295, MPLSCWFR)

